<template>
<highlightjs language="JavaScript" highlightAuto top :code="code" />
</template>
<script>
export default {
  setup () {
    const code = `
    const state = reactive({
      map: ref(null),
      mapBox: ref(null),
      draw: null,
      source: new VectorSource({
        wrapX: false // 禁止横向无限重复（底图渲染的时候会横向无限重复），设置了这个属性，可以让绘制的图形不跟随底图横向无限重复
      }),
      raster: new Tile({
        source: new XYZ({
          url: 'https://api.maptiler.com/maps/basic-4326/256/{z}/{x}/{y}.png?key=B3EG5uYPUvFucEWVoCa3',
          crossOrigin: ''
        })
      })
    })

    const init = () => {
      const styleFunction = (feature) => {
        const geometry = feature.getGeometry()
        const styles = [
          new Style({
            stroke: new Stroke({
              color: '#ffcc33',
              width: 2
            })
          })
        ]

        geometry.forEachSegment((start, end) => {
          const dx = end[0] - start[0]
          const dy = end[1] - start[1]
          const rotation = Math.atan2(dy, dx)
          styles.push(new Style({
            geometry: new Point(end),
            image: new Icon({
              src: require('@/assets/arrow.png'),
              anchor: [0.75, 0.5],
              rotateWithView: true,
              rotation: -rotation
            })
          }))
        })
        return styles
      }

      const vector = new VectorLayer({
        source: state.source,
        style: styleFunction
      })

      state.map = new Map({
        target: state.mapBox,
        layers: [state.raster, vector],
        view: new View({
          center: [0, 0],
          zoom: 3
        })
      })

      state.map.addInteraction(new Draw({
        source: state.source,
        type: 'LineString'
        // freehand: true // 自由绘制
      }))
    }
    `
    return {
      code
    }
  }
}
</script>
